#!/usr/bin/env python 
'''
Copyright (C) 2005, 2008 Aaron Spike, aaron@ekips.org

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
'''
import inkex, cspsubdiv, simplepath, cubicsuperpath, re
from cuft import gsd

uuconv = {'in':90.0, 'pt':1.25, 'px':1, 'mm':3.5433070866, 'cm':35.433070866, 'pc':15.0}
def unittouu(string):
	unit = re.compile('(%s)$' % '|'.join(uuconv.keys()))
	param = re.compile(r'(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)')

	p = param.match(string)
	u = unit.search(string)	
	if p:
		retval = float(p.string[p.start():p.end()])
	else:
		retval = 0.0
	if u:
		try:
			return retval * uuconv[u.string[u.start():u.end()]]
		except KeyError:
			pass
	return retval

class MyEffect(inkex.Effect):
    def __init__(self):
        inkex.Effect.__init__(self)
        self.OptionParser.add_option("-f", "--flatness",
            action="store", type="float", 
            dest="flat", default=1.0,
            help="Minimum flatness of the subdivided curves")
        self.gsd = gsd.GSD()
    def output(self):
        print self.gsd.outputGSD()
    def effect(self):
        #flat = self.options.flat
        ######################
        # set flattness here #
        ######################
        flat = 1
        ######################        
        scale = 25.4/90.0
        h = unittouu(self.document.xpath('/svg/@height')[0])
        w = unittouu(self.document.xpath('/svg/@width')[0])
        
        self.gsd.setPageSize(w*scale,h*scale)
        
        path = '//path'
        for node in self.document.xpath(path):
            d = node.get('d')
            sim = simplepath.parsePath(d)
            simplepath.scalePath(sim,scale,-scale)
            simplepath.translatePath(sim,0,h*scale)            
            p = cubicsuperpath.CubicSuperPath(sim)
            cspsubdiv.cspsubdiv(p, flat)
            for sub in p:
                points = [x[1] for x in sub]
                self.gsd.appendPolyline(points)


e = MyEffect()
e.affect()
